import logging


from ....common.cache import cache_validate, ValidationContext
from ....init.Global import configuration
from ...mapper._ChatHistoryCacheMapper import _chatHistoryCacheMapper
from ._UserChatHistoryService import _UserChatHistoryService


class _ChatHistoryCacheService:

    @classmethod
    async def get_history(cls, sessionId: int, limit: int = 10, ttl=60 * 60 * 2):
        if await _chatHistoryCacheMapper.exists(sessionId):
            result = await _UserChatHistoryService.get_by_session_id(sessionId, limit)
            logging.info(f"从数据库查找到:{result[::-1]}")
            await cls.set_history(sessionId, result, ttl)
        return await _chatHistoryCacheMapper.get_cache_by_session_id(sessionId, limit)

    @classmethod
    async def add_history(
        cls, sessionId: int, history: list[list[str]], ttl=60 * 60 * 2
    ):
        await _chatHistoryCacheMapper.add_cache_by_session_id(sessionId, history, ttl)
        await cls.validate(sessionId)

    @classmethod
    async def validate(cls, sessionId: int):
        """
        判断是否要弹出缓存
        并插入到数据库
        """
        length = await _chatHistoryCacheMapper.get_cache_length_by_session_id(sessionId)
        max_cache = configuration.cache.max_cache
        max_use_history = configuration.cache.max_use_history
        context = ValidationContext(
            session_id=sessionId,
            current_length=length,
            max_cache=max_cache,
            max_use_history=max_use_history,
            user_chat_history_service=_UserChatHistoryService,
            chat_history_cache_mapper=_chatHistoryCacheMapper,
            ttl=configuration.redis.time,
        )
        await cache_validate.handler(context)

    @classmethod
    async def set_history(
        cls, sessionId: int, history: list[list[str]], ttl=60 * 60 * 2
    ):
        await _chatHistoryCacheMapper.set_cache_by_session_id(sessionId, history, ttl)
